<template>
  <editor-layout class="edit" @ok="handleOk" v-on="$listeners" v-loading="loading" :loading="saveLoading">
    <el-form size="small" :model="model" :rules="rule" ref="form" @keyup.enter.native="handleOk()" label-width="110px">
      <el-row :gutter="10">
        <el-col v-if="currSetType === 'sql'" :span="8">
          <el-form-item label="数据源" prop="sourceId">
            <el-select v-model="model.sourceId">
              <el-option v-for="item in sourceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="数据集名称" prop="setName">
            <el-input v-model.trim="model.setName" placeholder="数据集名称" size="mini"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据集描述" prop="setDesc">
            <el-input v-model.trim="model.setDesc" placeholder="数据集描述" size="mini"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="currSetType === 'sql'" :gutter="10">
        <el-col :span="24" class="code-mirror-form">
          <el-form-item label="查询SQL">
            <div class="codemirror">
              <monaco-editor
                  v-model.trim="model.dynSentence"
                  language="sql"
                  style="height: 500px"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else-if="currSetType === 'http'">
        <el-form-item label="请求路径">
          <el-input v-model="httpForm.apiUrl" placeholder="请输入请求路径..." class="input-with-select" size="mini">
            <el-select
                v-model="httpForm.method"
                slot="prepend"
                placeholder="请选择"
            >
              <el-option label="GET" value="GET"></el-option>
              <el-option label="POST" value="POST"></el-option>
              <el-option label="PUT" value="PUT"></el-option>
              <el-option label="DELETE" value="DELETE"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="请求头">
          <el-input
              v-model.trim="httpForm.header"
              size="mini"
              placeholder="请输入请求头..."
          />
        </el-form-item>
        <el-form-item label="请求体">
          <el-input
              v-model.trim="httpForm.body"
              size="mini"
              placeholder="请输入请求体..."
          />
        </el-form-item>
      </el-row>

      <el-row :gutter="10">
        <el-col>
          <el-form label-width="100px" class="demo-ruleForm">
            <el-tabs
                v-model.trim="tabsActiveName"
                type="card"
                @tab-click="handleClickTabs"
            >
              <el-tab-pane label="查询参数" name="first">
                <el-button
                    v-if="tableData.length == 0"
                    type="text"
                    size="mini"
                    @click="addRow()"
                >添加
                </el-button>
                <el-table :data="tableData" border style="width: 100%">
                  <el-table-column
                      align="center"
                      label="序号"
                      type="index"
                      min-width="80"
                  />
                  <el-table-column label="参数名" align="center">
                    <template v-slot="scope">
                      <el-input
                          v-model.trim="tableData[scope.$index].paramName"
                          size="mini"
                          :disabled="
                            tableData[scope.$index].paramName == 'pageSize' ||
                              tableData[scope.$index].paramName == 'pageNumber'
                          "
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="描述" align="center">
                    <template v-slot="scope">
                      <el-input v-model.trim="tableData[scope.$index].paramDesc" size="mini"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="数据类型" align="center">
                    <template v-slot="scope">
                      <el-input v-model.trim="tableData[scope.$index].paramType" size="mini"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="示例值" align="center">
                    <template v-slot="scope">
                      <el-input v-model.trim="tableData[scope.$index].sampleItem" size="mini"/>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="200" align="center">
                    <template v-slot="scope">
                      <el-button
                          type="text"
                          size="mini"
                          @click.native.prevent="cutOutRow(scope.$index, tableData)"
                      >删除
                      </el-button>
                      <el-button
                          type="text"
                          size="mini"
                          @click="addRow(scope.row)"
                      >追加
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>

              <el-tab-pane label="测试预览" name="third">
                <div style="max-height: 400px; overflow: auto">
                  <vue-json-editor
                      v-model="cols"
                      :show-btns="false"
                      :mode="'code'"
                      lang="zh"
                      @json-change="onJsonChange"
                      @json-save="onJsonSave"
                  />
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-col>
      </el-row>

    </el-form>

    <simple-dialog v-bind.sync="dialog" @on-ok="onDialogOk"/>

  </editor-layout>
</template>

<script>

/**
 * Created by Administrator on 2023/2/5
 */
import vueJsonEditor from 'vue-json-editor';
import monacoEditor from '@/components/common/monaco/monaco-editor'
import simpleDialog from '@/components/common/dialog/simple-dialog'
import dialogMixin from '@/components/common/dialog/dialog-mixin'

import ruleEdit from './rule-edit'

import {postReportReportdatasourceListAll} from '@/api/dataSource'
import {postReportdatasetTestTransform, getReportdatasetInfoId, postReportdatasetSave, postReportdatasetUpdate} from '@/api/dateSet'


export default {
  name: 'edit',
  mixins: [dialogMixin],
  components: {
    monacoEditor,
    vueJsonEditor,
    simpleDialog
  },
  props: {
    id: [String, Number],
    setType: String
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      model: {
        sourceId: '',
        setName: '',
        setDesc: '',
        dynSentence: ''
      },
      httpForm: {
        apiUrl: '',
        method: '',
        header: '{"Content-Type":"application/json;charset=UTF-8"}',
        body: ''
      },
      rule: {
        setName: [
          { required: true, message: '数据集名称必填', trigger: 'blur' }
        ],
        sourceId: [
          { required: true, message: '数据源必选', trigger: 'change' }
        ]
      },
      updataDisabled: false,
      sourceList: [],
      tabsActiveName: 'first',
      cols: [],
      tableData: [
        {
          paramName: '',
          paramDesc: '',
          paramType: '',
          sampleItem: '',
          mandatory: true,
          requiredFlag: 1,
          validationRules: 'function verification(data){\n\t//自定义脚本内容\n\t//可返回true/false单纯校验键入的data正确性\n\t//可返回文本，实时替换,比如当前时间等\n\t//return "2099-01-01 00:00:00";\n\treturn true;\n}'
        }
      ],
      isRowData: {},
      isTestOk: false,
      currSetType: this.setType
    }
  },
  methods: {
    async init() {
      await this.loadDataSource()

      if (this.id) {
        this.loadForm()
      }
    },
    async loadDataSource() {
      // 获取数据源
      const res = await postReportReportdatasourceListAll({enableFlag: 1})
      const list = res || []
      this.sourceList = list.map(o => {
        return {
          label: o.sourceName,
          value: o.id
        }
      })
    },
    async loadForm() {
      this.loading = true
      const data = await getReportdatasetInfoId(this.id).catch(e => {
        this.loading = false
        throw new Error(e)
      })
      this.loading = false
      this.currSetType = data.setType
      this.model = data
      this.tableData = data.dataSetParamDtoList || []

      if(this.currSetType === 'http') {
        this.httpForm = JSON.parse(data.dynSentence)
      }

    },
    handleOk() {
      this.$refs.form.validate(ok => {
        if(!ok) return

        if(!this.isTestOk) {
          this.$message.error('请先测试预览，操作成功后便可保存！');
          return
        }

        console.info('model:', this.model)
        this.model.setType = this.currSetType
        const param = {...this.model}
        param.dataSetParamDtoList = this.tableData
        param.caseResult = JSON.stringify(this.cols)

        console.info('param:', param)

        let saveFn = postReportdatasetSave
        if(this.id) {
          saveFn = postReportdatasetUpdate
        }
        this.saveLoading = true
        saveFn(param).then(res => {
          this.saveLoading = false
          this.$notify.success('操作成功!')
          this.$emit('on-ok')
        }).catch(e => {
          this.$notify.error('保存数据集失败！')
          this.saveLoading = false
          throw new Error(e)
        })


      })
    },
    async handleClickTabs(tab) {
      if(this.currSetType === 'http') {
        // 针对http数据源
        console.log('http数据集', this.httpForm);
        this.model.dynSentence = JSON.stringify(this.httpForm);
      }

      if(tab.paneName === 'third') {
        this.isTestOk = false
        const params = {
          sourceId: this.model.sourceId,
          dynSentence: this.model.dynSentence,
          dataSetParamDtoList: this.tableData,
          setType: this.currSetType
        }

        console.info('params:', params)
        const res = await postReportdatasetTestTransform(params)
        this.cols = res
        this.isTestOk = true
      }

    },
    addRow(row) {
      this.tableData.push({
        paramName: '',
        paramDesc: '',
        paramType: '',
        sampleItem: '',
        mandatory: true,
        requiredFlag: 1,
        validationRules: 'function verification(data){\n\t//自定义脚本内容\n\t//可返回true/false单纯校验键入的data正确性\n\t//可返回文本，实时替换,比如当前时间等\n\t//return "2099-01-01 00:00:00";\n\treturn true;\n}'
      });
    },
    cutOutRow(index, rows) {
      rows.splice(index, 1);
    },
    permissionClick(row, index) {
      this.isRowData = row
      const fnCont = 'function verification(data){\n\t//自定义脚本内容\n\t//可返回true/false单纯校验键入的data正确性\n\t//可返回文本，实时替换,比如当前时间等\n\t//return "2099-01-01 00:00:00";\n\treturn true;\n}';
      const rule = row.validationRules || fnCont
      this.setDialog({
        comp: ruleEdit,
        height: '700px',
        props: {
          value: rule,
          data: row
        }
      })
    },
    onJsonChange() {
    },
    onJsonSave() {
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="less" scoped>
.edit {
  .code-mirror-form {
    /deep/ .el-form-item__content {
      height: 200px;
      overflow: hidden;
    }
  }

  .input-with-select {
    /deep/ .el-input__inner {
        min-width: 100px;
    }
  }
}
</style>
